package com.mojo.concurrent.practice;

/**
 * 多线程-有序打印
 * <pre>
 *    有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C，要求, 同时启动三个线程, 按顺序输出ABC
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2023, 广州九尾信息科技有限公司
 * @date 2023/2/21 14:10
 */
public class orderlyPrint {
    public static void main(String[] args) {
        Order order = new Order();
        new Thread(new OrderA(order)).start();
        new Thread(new OrderB(order)).start();
        new Thread(new OrderC(order)).start();
    }

    static class OrderA implements Runnable {
        Order order;

        public OrderA(Order order) {
            this.order = order;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (Order.class) {
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    if (order.i % 3 == 0) {
                        System.out.println("线程A>>>" + order.i);
                        order.i++;
                    }
                }
            }
        }
    }

    static class OrderB implements Runnable {
        Order order;

        public OrderB(Order order) {
            this.order = order;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (Order.class) {
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    if (order.i % 3 == 1) {
                        System.out.println("线程B>>>>" + order.i);
                        order.i++;
                    }
                }
            }
        }
    }

    static class OrderC implements Runnable {
        Order order;

        public OrderC(Order order) {
            this.order = order;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (Order.class) {
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    if (order.i % 3 == 2) {
                        System.out.println("线程C>>>>>" + order.i);
                        order.i++;
                    }
                }
            }
        }
    }

    static class Order {
        int i;
    }
}
